package com.xhorse.lockplatform.service.impl;

import com.xhorse.lockplatform.comm.enums.ResultEnum;
import com.xhorse.lockplatform.comm.exception.LockPlatFormException;
import com.xhorse.lockplatform.comm.model.ResponseLocation;
import com.xhorse.lockplatform.comm.service.BaseService;
import com.xhorse.lockplatform.comm.util.Paginator;
import com.xhorse.lockplatform.comm.util.RequestUtils;
import com.xhorse.lockplatform.dao.mapper.XhUsingLogMapper;
import com.xhorse.lockplatform.model.XhUsingLog;
import com.xhorse.lockplatform.model.pojo.XhUsingLogPojo;
import com.xhorse.lockplatform.service.UsingLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Service
public class UsingLogServiceImpl extends BaseService<XhUsingLogPojo> implements UsingLogService {


    @Autowired
    private XhUsingLogMapper xhUsingLogMapper;

    /**
     * 提交操作日志
     */
    @Override
    public void uploadUsinLog(XhUsingLog xhUsingLog) {
        xhUsingLogMapper.insertSelective(xhUsingLog);
    }

    /**
     * 后台获取操作日志
     */
    @Override
    public List<XhUsingLogPojo> getUsingLog(Paginator page, int type) {
        List<XhUsingLogPojo> list = new ArrayList<>();
        if (type == 1) { // 遥控生成
            list = this.listByOther(page, xhUsingLogMapper.selectRemotePagedList(page));
        } else if (type == 2) { // 钥匙解锁
            list = this.listByOther(page, xhUsingLogMapper.selectRenewPagedList(page));
        } else if (type == 3) { // 芯片生成
            list = this.listByOther(page, xhUsingLogMapper.selectChipPagedList(page));
        }
        for (XhUsingLogPojo xhUsingLogPojo : list) { // 根据经纬度定位
            if (!xhUsingLogPojo.getAddress().equals("")) {
                String[] GPSPoints = xhUsingLogPojo.getAddress().split(",");
                ResponseLocation location;
                try {
                    location = RequestUtils.getAdd(GPSPoints[0], GPSPoints[1]);
                } catch (IOException e) {
                    throw new LockPlatFormException(ResultEnum.FAILED.getCode(), "getUsingLog get Location,遇到异常", e);
                }
                String addressInfo = location.getResult()
                        .getFormatted_address()
                        + location.getResult().getSematic_description();
                xhUsingLogPojo.setAddressInfo(addressInfo);
            }
        }
        return list;
    }

}
